package com.system.util;

import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.system.constant.AliyunConstants;
import com.system.constant.QiniuyunConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Classname QiniuUtil
 * @Date 2023/10/10 10:27
 * @Created ZFC
 */
@Slf4j
public class QiniuUtil {


    // 创建七牛云配置对象
    private static Configuration cfg = new Configuration(Zone.autoZone());
    //密钥配置
    private static Auth auth = Auth.create(QiniuyunConstants.qiniuAccessKey, QiniuyunConstants.qiniusecretKey);

    /**
     * 获取token
     *
     * @return
     */
    public static String getUpToken() {
        return auth.uploadToken(QiniuyunConstants.qiniuBucketName);
    }

    public static String uploadFile(MultipartFile file) {
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀 dfdfdf.png
            String extension = originalFilename.substring(originalFilename.indexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            // 创建上传管理器
            UploadManager uploadManager = new UploadManager(cfg);

            //sm-frontend/2024/3/417a6320-a0be-4e90-a7ab-ebd1fe320269.png
            String directory = AliyunConstants.directory + StringUtils.yearAndMonthFolder() + objectName;

            // 执行文件上传
            Response response = uploadManager.put(file.getBytes(),directory , getUpToken());

            // 解析上传结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            String fileKey = putRet.key; // 获取上传文件的key http:/qiniuyun.zfc.life/sm-frontend/2024/3/bg1.gif

            log.info(directory," 资源上传成功！");

            // 返回文件在七牛云的访问URL
            return directory;
        } catch (Exception e) {
            e.printStackTrace();
            return "资源上传错误！";
        }
    }

    /**
     * @param file
     * @param folder 文件夹;例：test/
     * @return 图片地址
     * @throws IOException
     */
    public static String saveImage(MultipartFile file, String folder) throws IOException {
        try {
            //校验文件名中最后一个 "." 的位置
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            //获取后缀转成小写
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            //获取日期
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String currentDate = dateFormat.format(date);
            //生成一个当前日期文件夹
            folder = folder.concat(currentDate + "/");
            //
            String fileName = folder.concat(UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt);

            UploadManager uploadManager = new UploadManager(cfg);
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return QiniuyunConstants.qiniuImageDomain + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            return null;
        }
    }

    /**
     * 删除图片
     *
     * @param fileName 图片名称
     * @return
     */
    public static boolean delImages(String fileName) {

        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            //将图片地址分割；只获取目录后的地址；域名不要
            String[] split = fileName.split(QiniuyunConstants.qiniuImageDomain);
            //判断图片是否存在
            FileInfo stat = bucketManager.stat(QiniuyunConstants.qiniuBucketName, split[1]);
            if (stat != null) {
                bucketManager.delete(QiniuyunConstants.qiniuBucketName, split[1]);
                return true;
            }
            return false;
        } catch (QiniuException e) {
            throw new RuntimeException(e.response.toString());
        }
    }

    public static void main(String[] args) {

        delImages("http://qiniuyun.zfc.life/test/2023-10-10/383f7d35944f49f79b8d550aab23cb4b.png");
    }
}
